package cn.itrigger.mojos;

import cn.itrigger.config.VersionConfig;
import cn.itrigger.config.VersionLevelEnum;
import cn.itrigger.publish.UatVersionPublish;
import cn.itrigger.publish.VersionPublish;
import cn.itrigger.utils.GitOperatorUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

@Mojo(name = "uat")
public class ItriggerUatMojo extends ItriggerReleaseMojo {


    //uat环境默认不需要打标签
    @Parameter(property = "tag", readonly = true, defaultValue = "false")
    private String tag;
    //版本号的后缀
    @Parameter(property = "uatSubffix", defaultValue = "u")
    protected String uatSubffix;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (BooleanUtils.toBoolean(help)) {
            help();
            return;
        }


        System.out.println("开始发布UAT版本");
        // 切分支
        GitOperatorUtils.checkout(uatBranch);
        //拉代码
        GitOperatorUtils.pull(uatBranch);
        //本地变更重置
        GitOperatorUtils.reset();

        String[] diff = GitOperatorUtils.diff();
        if (null == diff || diff.length == 0){
            VersionConfig.VersionConfigBuilder builder = new VersionConfig.VersionConfigBuilder();
            VersionConfig config = null;
            try {
                config = builder.setNexusUrl(nexusUrl).setGitUrl(gitUrl).setEnv(env)
                        .setUatBranch(uatBranch).setProject(project).setTag(tag).setProdBranch(prodBranch)
                        .setVersionLevel(VersionLevelEnum.index(Integer.parseInt(versionLevel) - 1))
                        .setDailySubffix(dailySubffix).setUatSubffix(uatSubffix).setProdSubffix(prodSubffix)
                        .setUserName(userName).setUserEmail(userEmail)
                        .setName(name).setPassword(password).setFixVersionNumber(fixVersionNumber)
                        .setModule(module).setUpdateVersion(updateVersion).setDeploy(deploy).hasInstall(hasInstall)
                        .uatIsRelease(uatIsRelease)
                        .build();
            }catch (Exception e) {
                e.printStackTrace();
            }

            VersionPublish publish = new UatVersionPublish(config);
            publish.publish();

        }else {
            System.err.println("本地代码有修改，无法发布版本");
        }
    }

    @Override
    public void validate() throws MojoExecutionException {
        String version = project.getVersion();
        if (!version.endsWith("-SNAPSHOT") && !version.endsWith("u")) {
            throw new MojoExecutionException("版本号后缀格式不正确，version="+version);
        }
    }
}
